<?php

use Carbon\Carbon;

require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';

use google\appengine\api\cloud_storage\CloudStorageTools;

/* * ****************************************************************************
 * controllers\CarController
 * 
 * author  Laureta Xhaferaj
 * email   laureta@first.al
 * 
 * @function index
 * @function create
 * @function store
 * @function history
 * @function insert_history
 * @function edit
 * @function update
 * @function destroy
 * @function images_galery
 * @function docs_galery
 * @function upload_images
 * @function upload_docs
 * @function download_ownerCertDoc
 * @function download_sgsDoc
 * @function download_tplDoc
 * @function download_kaskoDoc
 * @function download_drivePermisDoc
 * @function download_interPermisDoc
 * @function download_authorizDoc
 * @function show
 * @function insurDocs_print
 * @function success_filter
 * @function warning_filter
 * @function danger_filter
 * *************************************************************************** */

class CarController extends \BaseController {

    public function __construct() {
        $this->beforeFilter('auth', array('only' => array('index')));
    }

    /**
     * Display a table with vehicle inforamtion.
     *
     * @return array
     */
    public function index() {
        $cars = DB::select('select * from cars');
        $result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis '
                        . 'from cars as c left join insur_docs as i  on i.car_id = c.id');
        $date = Carbon::now();
        $limit_date = Carbon::now()->addMonths(1);
        return View::make('pages.index', array(
                    'cars' => $cars,
                    'result' => $result,
                    'date' => $date,
                    'limit_date' => $limit_date,
        ));
    }

    /**
     * The form to insert a new vehicle
     *
     * @return array
     */
    public function create() {
        $classes = DB::table('classes')->orderBy('class', 'asc')
                        ->distinct()->lists('class', 'id');
        $color = array(
            '' => '',
            'Black' => Lang::get('messages.Black'),
            'Blue' => Lang::get('messages.Blue'),
            'Brown' => Lang::get('messages.Brown'),
            'Darkred' => Lang::get('messages.Darkred'),
            'Green' => Lang::get('messages.Green'),
            'Grey' => Lang::get('messages.Grey'),
            'Orange' => Lang::get('messages.Orange'),
            'Pearl' => Lang::get('messages.Pearl'),
            'Purple' => Lang::get('messages.Purple'),
            'Red' => Lang::get('messages.Red'),
            'Yellow' => Lang::get('messages.Yellow'),
            'Violet' => Lang::get('messages.Violet'),
            'White' => Lang::get('messages.White'),
        );

        return View::make('pages.create', array(
                    'classes' => $classes,
                    'color' => $color
        ));
    }

    /**
     * Store values in DB.
     *
     * @return Redirect or error
     */
    public function store() {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'desc' => Lang::get('messages.description'),
            'make' => Lang::get('messages.make'),
            'model' => Lang::get('messages.model'),
            'license' => Lang::get('messages.license'),
            'class' => Lang::get('messages.class'),
            'milage' => Lang::get('messages.milage'),
            'year' => Lang::get('messages.year'),
            'color' => Lang::get('messages.color'),
            'vin' => Lang::get('messages.vin'),
            'fuel' => Lang::get('messages.fuel'),
            'trans' => Lang::get('messages.transmission'),
            'status' => Lang::get('messages.status'),
            'nr_people' => Lang::get('messages.nr_people'),
            'nr_suitcase' => Lang::get('messages.nr_suitcase'),
            'nr_doors' => Lang::get('messages.nr_doors'),
            'air_condition' => Lang::get('messages.air_condition'),
            'fueltype' => Lang::get('messages.fuel_type'),
        );
        $rules = array(
            "desc" => "required",
            "make" => "required",
            "model" => "required",
            "license" => "required",
            "class" => "required",
            "milage" => "required",
            "year" => "required",
            "color" => "required",
            "vin" => "required",
            "fuel" => "required",
            "trans" => "required",
            "status" => "required",
            "nr_people" => "required",
            "nr_suitcase" => "required",
            "nr_doors" => "required",
            "air_condition" => "required",
            "fueltype" => "required"
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        if ($validation->passes()) {
            $data = new Car;
            $data->Description = Input::get('desc');
            $data->License = Input::get('license');
            $data->Make = Input::get('make');
            $data->Model = Input::get('model');
            $data->Milage = Input::get('milage');
            $data->year = Input::get('year');
            $data->Color = Input::get('color');
            $data->vin = Input::get('vin');
            $data->class = Input::get('class');
            $data->fuel = Input::get('fuel');
            $data->trans = Input::get('trans');
            $data->status = Input::get('status');
            $data->nr_people = Input::get('nr_people');
            $data->nr_suitcase = Input::get('nr_suitcase');
            $data->nr_doors = Input::get('nr_doors');
            $data->air_condition = Input::get('air_condition');
            $data->comment = Input::get('comment');
            $data->fueltype = Input::get('fueltype');
            $data->purchase_price = Input::get('purchase_price');
            $data->user_id = Auth::user()->id;
            $data->save();

            //insert table insert history
            $car_insert = new CarInsert;
            $car_insert->Description = Input::get('desc');
            $car_insert->License = Input::get('license');
            $car_insert->Make = Input::get('make');
            $car_insert->Model = Input::get('model');
            $car_insert->Milage = Input::get('milage');
            $car_insert->year = Input::get('year');
            $car_insert->Color = Input::get('color');
            $car_insert->vin = Input::get('vin');
            $car_insert->class = Input::get('class');
            $car_insert->fuel = Input::get('fuel');
            $car_insert->trans = Input::get('trans');
            $car_insert->status = Input::get('status');
            $car_insert->nr_people = Input::get('nr_people');
            $car_insert->nr_suitcase = Input::get('nr_suitcase');
            $car_insert->nr_doors = Input::get('nr_doors');
            $car_insert->air_condition = Input::get('air_condition');
            $car_insert->comment = Input::get('comment');
            $car_insert->fueltype = Input::get('fueltype');
            $car_insert->user_id = Auth::user()->id;
            $car_insert->purchase_price = Input::get('purchase_price');
            $car_insert->save();

            // redirect
            return Response::json(["redirect_to" => "/"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            } else {
                $data['errors'] = $validation->errors();
                return View::make('pages.create', $data);
            }
        }
    }

    /**
     * Display the history of changes.
     *
     * @return array
     */
    public function history() {
        $car_update = DB::select('select r.*, u.username, c.make, c.license '
                        . 'from revisions as r left join users as u on u.id=r.user_id '
                        . 'left join cars as c on c.id = r.revisionable_id '
                        . 'where r.revisionable_type="Car"');
        $insurdoc_update = DB::select('select r.*, u.username, i.car_id,i.id, c.make, c.license, c.id '
                        . 'from revisions as r '
                        . 'left join users as u on u.id=r.user_id '
                        . 'left join insur_docs as i on i.id=r.revisionable_id '
                        . 'left join cars as c on c.id=i.car_id '
                        . 'where r.revisionable_type="InsurDoc"');
        $repair_parts = DB::select('select r.*, u.username from revisions as r '
                        . 'left join users as u on u.id=r.user_id '
                        . 'where r.revisionable_type="RepairPart" AND r.key="repair"');

        return View::make('pages.history', array(
                    'car_update' => $car_update,
                    'insurdoc_update' => $insurdoc_update,
                    'repair_parts' => $repair_parts
        ));
    }

    /**
     * Display the history of insert.
     *
     * @return array
     */
    public function insert_history() {
        $car = DB::select('select c.*, u.username from car_inserts as c '
                        . 'left join users as u on u.id = c.user_id');

        $insur_docs = DB::select('select i.*, u.username, c.Make, c.License '
                        . 'from insurdocs_inserts as i '
                        . 'left join users as u on u.id = i.user_id '
                        . 'left join cars as c on c.id = i.car_id');

        $maintenance = DB::select('select m.*, u.username, c.Make, c.License, 
            p.process from maint_inserts as m
        left join users as u on u.id = m.user_id
        left join cars as c on c.id = m.car_id
        left join processes as p
        on p.id = m.process_id');
        $repairs = DB::select('select r.*, p.repair, u.username, c.Make, '
                        . 'c.License from repairs_inserts as r '
                        . 'left join users as u '
                        . 'on u.id = r.user_id '
                        . 'left join cars as c '
                        . 'on c.id = r.car_id '
                        . 'left join repair_parts as p on p.id = r.repair_id');
        $repair_parts = DB::select('select p.*, u.username from repairparts_inserts as p '
                        . 'left join users as u on u.id=p.user_id');
        $processes = DB::select('select p.*, u.username from processes_inserts as p '
                        . 'left join users as u on u.id=p.user_id');
        return View::make('pages.insert_history', array(
                    'car' => $car,
                    'insur_docs' => $insur_docs,
                    'maintenance' => $maintenance,
                    'repairs' => $repairs,
                    'repair_parts' => $repair_parts,
                    'processes' => $processes
        ));
    }

    /**
     * Display the history of insert.
     *
     * @return array
     */
    public function delete_history() {
        $repairs = DB::select('select r.*, p.repair, u.username, c.Make, '
                        . 'c.License from repairs_deletes as r '
                        . 'left join users as u '
                        . 'on u.id = r.user_id '
                        . 'left join cars as c '
                        . 'on c.id = r.car_id '
                        . 'left join repair_parts as p on p.id = r.repair_id');
        $repair_parts = DB::select('select p.*, u.username from repair_parts_deletes as p
               left join users as u on u.id=p.user_id ');
        $processes = DB::select('select p.*, u.username from processes_deletes as p '
                        . 'left join users as u on u.id=p.user_id');

        return View::make('pages.delete_history', array(
                    'repairs' => $repairs,
                    'repair_parts' => $repair_parts,
                    'processes' => $processes
        ));
    }

    /**
     * Edit vehicle informations.
     *
     * @param  int  $id
     * @return array
     */
    public function edit($id) {
        $values = DB::select('select * from cars where id = ?', array($id));
        $classes = DB::table('classes')->orderBy('class', 'asc')
                        ->distinct()->lists('class', 'id');
        $class = DB::select('select class from cars where id = ?', array($id)); // this returns array with 1 element of stdClass
        $classId = isset($class[0]->class) ? $class[0]->class : '';
        $classArray = DB::select('select * from classes where id = ?', array($classId));
        $color = array(
            '' => '',
            'Black' => Lang::get('messages.Black'),
            'Blue' => Lang::get('messages.Blue'),
            'Brown' => Lang::get('messages.Brown'),
            'Darkred' => Lang::get('messages.Darkred'),
            'Green' => Lang::get('messages.Green'),
            'Grey' => Lang::get('messages.Grey'),
            'Orange' => Lang::get('messages.Orange'),
            'Pearl' => Lang::get('messages.Pearl'),
            'Purple' => Lang::get('messages.Purple'),
            'Red' => Lang::get('messages.Red'),
            'Yellow' => Lang::get('messages.Yellow'),
            'Violet' => Lang::get('messages.Violet'),
            'White' => Lang::get('messages.White'),
        );
        return View::make('pages.edit', array(
                    'values' => $values,
                    'class' => $classArray,
                    'id' => $id,
                    'color' => $color,
                    'classes' => $classes
        ));
    }

    /**
     * Update vehicle data in DB.
     *
     * @param  int  $id
     * @return redirect or error
     */
    public function update($id) {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'desc' => Lang::get('messages.description'),
            'make' => Lang::get('messages.make'),
            'model' => Lang::get('messages.model'),
            'license' => Lang::get('messages.license'),
            'class' => Lang::get('messages.class'),
            'milage' => Lang::get('messages.milage'),
            'year' => Lang::get('messages.year'),
            'color' => Lang::get('messages.color'),
            'vin' => Lang::get('messages.vin'),
            'fuel' => Lang::get('messages.fuel'),
            'trans' => Lang::get('messages.transmission'),
            'status' => Lang::get('messages.status'),
            'nr_people' => Lang::get('messages.nr_people'),
            'nr_suitcase' => Lang::get('messages.nr_suitcase'),
            'nr_doors' => Lang::get('messages.nr_doors'),
            'air_condition' => Lang::get('messages.air_condition'),
            'fueltype' => Lang::get('messages.fuel_type')
        );
        $rules = array(
            "desc" => "required",
            "make" => "required",
            "model" => "required",
            "license" => "required",
            "class" => "required",
            "milage" => "required",
            "year" => "required",
            "color" => "required",
            "vin" => "required",
            "fuel" => "required",
            "trans" => "required",
            "status" => "required",
            "nr_people" => "required",
            "nr_suitcase" => "required",
            "nr_doors" => "required",
            "air_condition" => "required",
            "fueltype" => "required"
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        if ($validation->passes()) {
            $car = Car::find($id);
            $car->Description = Input::get('desc');
            $car->License = Input::get('license');
            $car->Make = Input::get('make');
            $car->Model = Input::get('model');
            $car->Milage = Input::get('milage');
            $car->year = Input::get('year');
            $car->Color = Input::get('color');
            $car->vin = Input::get('vin');
            $car->class = Input::get('class');
            $car->fuel = Input::get('fuel');
            $car->trans = Input::get('trans');
            $car->status = Input::get('status');
            $car->nr_people = Input::get('nr_people');
            $car->nr_suitcase = Input::get('nr_suitcase');
            $car->nr_doors = Input::get('nr_doors');
            $car->air_condition = Input::get('air_condition');
            $car->fueltype = Input::get('fueltype');
            $car->purchase_price = Input::get('purchase_price');
            $car->comment = Input::get('comment');
            $car->save();
            return Response::json(["redirect_to" => "/"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            } else {
                $data['errors'] = $validation->errors();
                return View::make('pages.edit', $data);
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return array
     */
    public function destroy($id) {
        //
    }

    /**
     * Form of images upload.
     *
     * @param  int  $id
     * @return array
     */
    public function images_galery($id) {
        $options = ['gs_bucket_name' => 'national-test.appspot.com'];
        $upload_url = CloudStorageTools::createUploadUrl('/upload_images', $options);
        $values = DB::select('select * from cars where id=?', array($id));
        return View::make('pages.upload_images', array(
                    'values' => $values,
                    'upload_url' => $upload_url
        ));
    }

    /**
     * Form of docs upload.
     *
     * @param  int  $id
     * @return array
     */
    public function docs_galery($id) {
        $options = ['gs_bucket_name' => 'national-test.appspot.com'];
        $upload_url = CloudStorageTools::createUploadUrl('/upload_docs', $options);
        $values = DB::select('select * from cars where id=?', array($id));
        return View::make('pages.upload_docs', array(
                    'values' => $values,
                    'upload_url' => $upload_url,
        ));
    }

    /**
     * Insert image in gs and DB.
     *
     * @return response
     */
    public function upload_images() {
        if (Input::hasFile('uploaded_files')) {
            $id = Input::get('id_value');
            $options = ['gs' => ['Content-Type' => 'text/plain']];
            $random = str_random(10);
            $ctx = stream_context_create($options);
            if (false == rename($_FILES['uploaded_files']['tmp_name'], 'gs://images_upload/' . $random . $id, $ctx)) {
                die('Could not rename.');
            }
            $car = Car::find($id);
            $car->Pic = 'gs://images_upload/' . $random . $id;
            $car->save();

            $car_insert = CarInsert::find($id);
            if ($car_insert != NULL) {
                $car_insert->Pic = 'gs://images_upload/' . $random . $id;
                $car_insert->save();
            }
            return Redirect::to('car/' . $id);
        } else {
            $id = Input::get('id_value');
            return Redirect::to('images_galery/' . $id)->with('message', Lang::get('messages.upload_fail'));
        }
    }

    /**
     * Insert docs in gs and DB.
     *
     * @return response
     */
    public function upload_docs() {
        if ((Input::file('owner_cert_doc') != NULL) || (Input::file('sgs_doc') != NULL) || (Input::file('tpl_doc') != NULL) || (Input::file('kasko_doc') != NULL) || (Input::file('drive_permis_doc') != NULL || Input::file('inter_permis_doc') != NULL || Input::file('authoriz_doc') != NULL)) {
            $car_id = Input::get('id_value');
            $id = DB::select('select id from insur_docs where car_id=?', array($car_id));
            $id_insert = DB::select('select id from insurdocs_inserts '
                            . 'where car_id=?', array($car_id));
            $options = ['gs' => ['Content-Type' => 'text/plain']];
            $ctx = stream_context_create($options);
            //ownership certificate documentations
            $random_owner = str_random(5);
            if (Input::hasFile('owner_cert_doc')) {
                $owner_input = Input::get('owner_cert_doc');
                $owner_cert_doc = $_FILES['owner_cert_doc']['name'];
                if (false == rename($_FILES['owner_cert_doc']['tmp_name'], 'gs://docs_upload/' .
                                $random_owner . '_' . $owner_cert_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //sgs docs
            if (Input::hasFile('sgs_doc')) {
                $random_sgs = str_random(5);
                $sgs_doc = $_FILES['sgs_doc']['name'];
                if (false == rename($_FILES['sgs_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_sgs . '_' . $sgs_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //tpl docs
            if (Input::hasFile('tpl_doc')) {
                $random_tpl = str_random(5);
                $tpl_doc = $_FILES['tpl_doc']['name'];
                if (false == rename($_FILES['tpl_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_tpl . '_' . $tpl_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //kasko docs
            if (Input::hasFile('kasko_doc')) {
                $random_kasko = str_random(5);
                $kasko_doc = $_FILES['kasko_doc']['name'];
                if (false == rename($_FILES['kasko_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_kasko . '_' . $kasko_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //drive permissions docs
            if (Input::hasFile('drive_permis_doc')) {
                $random_drive_permis = str_random(5);
                $drive_permis_doc = $_FILES['drive_permis_doc']['name'];
                if (false == rename($_FILES['drive_permis_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_drive_permis . '_' . $drive_permis_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //inter permissions docs
            if (Input::hasFile('inter_permis_doc')) {
                $random_inter_permis = str_random(5);
                $inter_permis_doc = $_FILES['inter_permis_doc']['name'];
                if (false == rename($_FILES['inter_permis_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_inter_permis . '_' . $inter_permis_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            //authoriz doc
            if (Input::hasFile('authoriz_doc')) {
                $random_authoriz = str_random(5);
                $authoriz_doc = $_FILES['authoriz_doc']['name'];
                if (false == rename($_FILES['authoriz_doc']['tmp_name'], 'gs://docs_upload/'
                                . $random_authoriz . '_' . $authoriz_doc, $ctx)) {
                    die('Could not rename.');
                }
            }
            if ($id != NULL) {
                $car = InsurDoc::find($id[0]->id);
                if (Input::hasFile('owner_cert_doc')) {
                    $car->owner_cert_doc = 'gs://docs_upload/' . $random_owner . '_' . $owner_cert_doc;
                }
                if (Input::hasFile('sgs_doc')) {
                    $car->sgs_doc = 'gs://docs_upload/' . $random_sgs . '_' . $sgs_doc;
                }
                if (Input::hasFile('tpl_doc')) {
                    $car->tpl_doc = 'gs://docs_upload/' . $random_tpl . '_' . $tpl_doc;
                }
                if (Input::hasFile('kasko_doc')) {
                    $car->kasko_doc = 'gs://docs_upload/' . $random_kasko . '_' . $kasko_doc;
                }
                if (Input::hasFile('drive_permis_doc')) {
                    $car->drive_permis_doc = 'gs://docs_upload/' . $random_drive_permis . '_' . $drive_permis_doc;
                }
                if (Input::hasFile('inter_permis_doc')) {
                    $car->inter_permis_doc = 'gs://docs_upload/' . $random_inter_permis . '_' . $inter_permis_doc;
                }
                if (Input::hasFile('authoriz_doc')) {
                    $car->authoriz_doc = 'gs://docs_upload/' . $random_authoriz . '_' . $authoriz_doc;
                }
                $car->save();
                if (!empty($id_insert)) {
                    $car_insert = InsurdocsInsert::find($id_insert[0]->id);
                    if (Input::hasFile('owner_cert_doc')) {
                        $car_insert->owner_cert_doc = 'gs://docs_upload/' . $owner_cert_doc . '_' . $owner_cert_doc;
                    }
                    if (Input::hasFile('sgs_doc')) {
                        $car_insert->sgs_doc = 'gs://docs_upload/' . $random_sgs . '_' . $sgs_doc;
                    }
                    if (Input::hasFile('tpl_doc')) {
                        $car_insert->tpl_doc = 'gs://docs_upload/' . $random_tpl . '_' . $tpl_doc;
                    }
                    if (Input::hasFile('kasko_doc')) {
                        $car_insert->kasko_doc = 'gs://docs_upload/' . $random_kasko . '_' . $kasko_doc;
                    }
                    if (Input::hasFile('drive_permis_doc')) {
                        $car_insert->drive_permis_doc = 'gs://docs_upload/' . $random_drive_permis . '_' . $drive_permis_doc;
                    }
                    if (Input::hasFile('inter_permis_doc')) {
                        $car_insert->inter_permis_doc = 'gs://docs_upload/' . $random_inter_permis . '_' . $inter_permis_doc;
                    }
                    if (Input::hasFile('authoriz_doc')) {
                        $car_insert->authoriz_doc = 'gs://docs_upload/' . $random_authoriz . '_' . $authoriz_doc;
                    }
                    $car_insert->save();
                }
                return Redirect::to('car/' . $car_id);
            } elseif ($id == NULL) {
                $car_id = Input::get('id_value');
                return Redirect::to('docs_galery/' . $car_id)->with('message', Lang::get('messages.insur_doc_empty'));
            }
        } else {
            $car_id = Input::get('id_value');
            return Redirect::to('docs_galery/' . $car_id)->with('message', Lang::get('messages.upload_fail'));
        }
    }

    /**
     * Download documentations.
     * 
     * @function download_ownerCertDoc
     * @function download_sgsDoc
     * @function download_tplDoc
     * @function download_kaskoDoc
     * @function download_drivePermisDoc
     * @function download_interPermisDoc
     * @function download_authorizDoc
     */
    public function download_ownerCertDoc($id) {
        $file_download = DB::select('select owner_cert_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->owner_cert_doc);
        $file = end($filename);
        CloudStorageTools::serve($file_download[0]->owner_cert_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_sgsDoc($id) {
        $file_download = DB::select('select sgs_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->sgs_doc);
        $file = end($filename);
        CloudStorageTools::serve($file_download[0]->sgs_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_tplDoc($id) {
        $file_download = DB::select('select tpl_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->tpl_doc);
        $file = end($filename);

        CloudStorageTools::serve($file_download[0]->tpl_doc, ['save_as' => '' . $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_kaskoDoc($id) {
        $file_download = DB::select('select kasko_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->kasko_doc);
        $file = end($filename);

        CloudStorageTools::serve($file_download[0]->kasko_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_drivePermisDoc($id) {
        $file_download = DB::select('select drive_permis_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->drive_permis_doc);
        $file = end($filename);

        CloudStorageTools::serve($file_download[0]->drive_permis_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_interPermisDoc($id) {
        $file_download = DB::select('select inter_permis_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->inter_permis_doc);
        $file = end($filename);

        CloudStorageTools::serve($file_download[0]->inter_permis_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    public function download_authorizDoc($id) {
        $file_download = DB::select('select authoriz_doc from insur_docs where car_id=?', array($id));
        $filename = explode('_', $file_download[0]->authoriz_doc);
        $file = end($filename);

        CloudStorageTools::serve($file_download[0]->authoriz_doc, ['save_as' => $file,
            'content_type' => 'text/plain']);
        dd(header('Content-Disposition: download;filename=' . $file));
    }

    /**
     * Display the info about a specific vehicle.
     *
     * @param  int  $id
     * @return array
     */
    public function show($id) {
        $current_date = Carbon::now();
        $insur_docs = DB::select('select * from insur_docs where car_id = ?', array($id));
        $values = DB::select('select c.*,i.id as insur_docs_id, i.sgs, i.tpl, i.kasko, i.inter_permis from cars as c '
                        . 'left join insur_docs as i  on i.car_id = c.id where c.id = ?', array($id));
        $class = DB::select('select class from cars where id = ?', array($id));
        $classId = isset($class[0]->class) ? $class[0]->class : '';
        $classArray = DB::select('select * from classes where id = ?', array($classId));
        $date = Carbon::now();
        $limit_date = Carbon::now()->addMonths(1);
        $counter = 0;
        $maintenance = DB::select('SELECT m.*, u.username,u.first_name, c.milage, p.id, p.process, s.name
                      FROM maintenances as m
                        LEFT JOIN users AS u
                          ON u.id = m.user_id
                        LEFT JOIN cars AS c
                          ON c.id = m.car_id
                        LEFT JOIN processes as p
                          ON p.id = m.process_id
                        LEFT JOIN services as s
                          ON s.id = m.service_id
                        INNER JOIN (SELECT id from maintenances as m3
                                     WHERE maintenance_date = 
                                    (SELECT MAX(m2.maintenance_date) 
                                     FROM maintenances m2 WHERE m2.car_id = m3.car_id 
                                     AND m2.process_id = m3.process_id)) AS l ON l.id = m.id
                        WHERE m.car_id = "' . $id . '"
                      Group by m.car_id, m.process_id');
        $maintenance_status = DB::select('SELECT m.*, c.milage, p.id, p.process
                      FROM maintenances as m
                        LEFT JOIN cars AS c
                          ON c.id = m.car_id
                        LEFT JOIN processes as p
                          ON p.id = m.process_id
                        INNER JOIN (SELECT id from maintenances as m3
                                     WHERE maintenance_date = 
                                    (SELECT MAX(m2.maintenance_date) 
                                     FROM maintenances m2 WHERE m2.car_id = m3.car_id 
                                     AND m2.process_id = m3.process_id)) AS l ON l.id = m.id
                        WHERE m.car_id = "' . $id . '"
                      Group by m.car_id, m.process_id');
        $file_download = DB::select('select owner_cert_doc,sgs_doc,tpl_doc,'
                        . 'kasko_doc,drive_permis_doc, inter_permis_doc,authoriz_doc '
                        . ' from insur_docs where car_id=?', array($id));
        if (!empty($file_download)) {

            $owner_cert_path = $file_download[0]->owner_cert_doc;
            $sgs_path = $file_download[0]->sgs_doc;
            $tpl_path = $file_download[0]->tpl_doc;
            $kasko_path = $file_download[0]->kasko_doc;
            $drive_permis_path = $file_download[0]->drive_permis_doc;
            $inter_permis_path = $file_download[0]->inter_permis_doc;
            $authoriz_path = $file_download[0]->authoriz_doc;
            $owner_cert_filename = explode('_', $owner_cert_path);
            $sgs_filename = explode('_', $sgs_path);
            $tpl_filename = explode('_', $tpl_path);
            $kasko_filename = explode('_', $kasko_path);
            $drive_permis_filename = explode('_', $drive_permis_path);
            $inter_permis_filename = explode('_', $inter_permis_path);
            $authoriz_filename = explode('_', $authoriz_path);
            $object_image_file = DB::select('select Pic from cars where id=?', array($id));

            if (!empty($object_image_file[0]->Pic)) {
                $image = CloudStorageTools::getImageServingUrl($object_image_file[0]->Pic, ["secure_url" => true]);
                return View::make(
                                'pages.desc', array(
                            'values' => $values,
                            'class' => $classArray,
                            'date' => $date,
                            'limit_date' => $limit_date,
                            'maintenance' => $maintenance,
                            'insur_docs' => $insur_docs,
                            'image' => $image,
                            'maintenance_status' => $maintenance_status,
                            'current_date' => $current_date,
                            'counter' => $counter,
                            'owner_cert_filename' => end($owner_cert_filename),
                            'sgs_filename' => end($sgs_filename),
                            'tpl_filename' => end($tpl_filename),
                            'kasko_filename' => end($kasko_filename),
                            'drive_permis_filename' => end($drive_permis_filename),
                            'inter_permis_filename' => end($inter_permis_filename),
                            'authoriz_filename' => end($authoriz_filename)
                ));
            } elseif (empty($object_image_file[0]->Pic)) {
                $object_image_file2 = 'gs://images_upload/no-image.png';
                $image = CloudStorageTools::getImageServingUrl($object_image_file2, ["secure_url" => true]);
                return View::make(
                                'pages.desc', array(
                            'values' => $values,
                            'class' => $classArray,
                            'date' => $date,
                            'limit_date' => $limit_date,
                            'maintenance' => $maintenance,
                            'insur_docs' => $insur_docs,
                            'image' => $image,
                            'maintenance_status' => $maintenance_status,
                            'current_date' => $current_date,
                            'counter' => $counter,
                            'owner_cert_filename' => end($owner_cert_filename),
                            'sgs_filename' => end($sgs_filename),
                            'tpl_filename' => end($tpl_filename),
                            'kasko_filename' => end($kasko_filename),
                            'drive_permis_filename' => end($drive_permis_filename),
                            'inter_permis_filename' => end($inter_permis_filename),
                            'authoriz_filename' => end($authoriz_filename)
                ));
            }
        } elseif (empty($file_download)) {
            $object_image_file = DB::select('select Pic from cars where id=?', array($id));
            if (!empty($object_image_file[0]->Pic)) {
                $image = CloudStorageTools::getImageServingUrl($object_image_file[0]->Pic, ["secure_url" => true]);
                return View::make('pages.desc', array(
                            'values' => $values,
                            'class' => $classArray,
                            'date' => $date,
                            'limit_date' => $limit_date,
                            'maintenance' => $maintenance,
                            'insur_docs' => $insur_docs,
                            'image' => $image,
                            'maintenance_status' => $maintenance_status,
                            'current_date' => $current_date,
                            'counter' => $counter,
                ));
            } elseif (empty($object_image_file[0]->Pic)) {
                $object_image_file2 = 'gs://images_upload/no-image.png';
                $image = CloudStorageTools::getImageServingUrl($object_image_file2, ["secure_url" => true]);
                return View::make('pages.desc', array(
                            'values' => $values,
                            'class' => $classArray,
                            'date' => $date,
                            'limit_date' => $limit_date,
                            'maintenance' => $maintenance,
                            'insur_docs' => $insur_docs,
                            'maintenance_status' => $maintenance_status,
                            'image' => $image,
                            'current_date' => $current_date,
                            'counter' => $counter,
                ));
            }
        }
    }

    /**
     * Display the report of insurances & docs.
     *
     * @return array
     */
    public function insurDocs_print() {
        $values = DB::select('select c.id, c.Make, c.License, i.* from insur_docs as i '
                        . 'left join cars as c '
                        . 'on c.id=i.car_id ');
        $limit_date = Carbon::now()->addMonths(1);
        $date = Carbon::now();
        return View::make('pages.insurDocs_report', array(
                    'date' => $date,
                    'limit_date' => $limit_date,
                    'values' => $values
        ));
    }

    /**
     * Display the vehicles that have tpl,sgs,kasko and inter_permissions valid.
     *
     * @return array
     */
    public function success_filter() {
        $cars = DB::select('select * from cars');
        $result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis '
                        . 'from cars as c left join insur_docs as i  on i.car_id = c.id');
        $date = Carbon::now();
        $limit_date = Carbon::now()->addMonths(1);
        return View::make('pages.success_filter', array(
                    'cars' => $cars,
                    'result' => $result,
                    'date' => $date,
                    'limit_date' => $limit_date,
        ));
    }

    /**
     * Display the vehicles that have tpl,sgs,kasko and inter_permissions in limit.
     *
     * @return array
     */
    public function warning_filter() {
        $cars = DB::select('select * from cars');
        $result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis '
                        . 'from cars as c left join insur_docs as i  on i.car_id = c.id');
        $date = Carbon::now();
        $limit_date = Carbon::now()->addMonths(1);
        return View::make('pages.warning_filter', array(
                    'cars' => $cars,
                    'result' => $result,
                    'date' => $date,
                    'limit_date' => $limit_date,
        ));
    }

    /**
     * Display the vehicles that have tpl,sgs,kasko and inter_permissions expired.
     *
     * @return array
     */
    public function danger_filter() {
        $cars = DB::select('select * from cars');
        $result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis '
                        . 'from cars as c left join insur_docs as i  on i.car_id = c.id');
        $date = Carbon::now();
        $limit_date = Carbon::now()->addMonths(1);
        return View::make('pages.danger_filter', array(
                    'cars' => $cars,
                    'result' => $result,
                    'date' => $date,
                    'limit_date' => $limit_date,
        ));
    }

    public function destroy_ownerCert($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->owner_cert_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_sgs($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->sgs_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_tpl($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->tpl_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_kasko($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->kasko_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_drivePermis($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->drive_permis_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_interPermis($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->inter_permis_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

    public function destroy_authoriz($id) {
        $data = InsurDoc::find($id);
        $car_id = DB::select('select car_id from insur_docs where id=?', array($id));
        $data->authoriz_doc = "";
        $data->save();
        return Redirect::to('../../car/' . $car_id[0]->car_id);
    }

}
